﻿function AzureOnlineQueuesListView(context) {

    var self = this;

    var spinner = new SpinnerModel();

    var queues = context.queues.queues;

    var spaRuntime = context.spaRuntime;

    var queueDetailsRoute = spaRuntime.findRouteByName('queueMessages');

    var filter = ko.observable('');
    
    var details = new AzureOnlineQueueCreateDetailsView(context);

    var filteredQueues = ko.computed(function () {
        var ques = queues();
        var f = filter();
        if (utils.isNullOrWhiteSpace(f)) return ques;
        var wildcard = new Wildcard(f);
        var res = [];
        for (var i = 0; i < ques.length; i++) {
            var cnt = ques[i];
            if (wildcard.match(cnt.name())) {
                res.push(cnt);
            }
        }
        return res;
    });
    
    function reload() {
        var api = context.api();
        spinner.enter();
        api.queues.listQueues({
            success: function (raw) {
                spinner.leave();
                var res = [];
                var $doc = $(raw);

                var $items = $doc.find('Queues Queue');
                $items.each(function () {
                    res.push(new AzureOnlineQueue($(this)));
                });

                queues(res);
            },
            error: function () {
                spinner.leave();
                queues([]);
                return 'notify';
            }
        });
    }

    function removeQueue(queue) {
        var api = context.api();
        spinner.enter();
        api.queues.removeQueue({
            queue: queue.name(),
            success: function () {
                spinner.leave();
                context.queues.removeQueue(queue);
            },
            error: function () {
                spinner.leave();
                return 'notify';
            }
        });
    }

    context.api.subscribe(function () {
        var api = context.api();
        if (api) {
            reload();
        }
    });

    ko.computed(function () {
        filter(context.queues.queuesSettings().getItem('quickSearch') || '');
    }).extend({ throttle: 10 });

    ko.computed(function () {
        context.queues.queuesSettings().setItem('quickSearch', filter());
    }).extend({ throttle: 10 });
    
    self.getQueueDetailsUrl = function (blob) {
        return queueDetailsRoute.formatHash({
            queueName: blob.name()
        });
    };

    self.context = context;
    self.spinner = spinner;
    self.filter = filter;
    self.reload = reload;
    self.removeQueue = removeQueue;
    self.queues = queues;
    self.filteredQueues = filteredQueues;
    self.details = details;
}